import random
import time
import uuid

import requests
import streamlit as st
from langserve import RemoteRunnable

st.set_page_config(page_title='知影', page_icon='clapper', layout="wide", initial_sidebar_state='auto',
                   menu_items={'About': '# This is a header. This is an *extremely* cool app!'})

# 标题和模型配置按钮
st.title("🎬知影")

# 创建一个空的占位符用于登录表单
login_form = st.empty()

# 登录表单
if "token" not in st.session_state:
    with login_form.form("login_form"):
        st.write("请登录以继续")
        username = st.text_input("用户名")
        password = st.text_input("密码", type="password")
        submitted = st.form_submit_button("登录")

        if submitted:
            response = requests.post('http://localhost:8000/user/login',
                                     json={"username": username, "password": password})
            if response.status_code == 200 and response.json().get('code') == "200":
                st.session_state["token"] = response.json()["data"]["token"]
                # headers = {"Authorization": f"Bearer {st.session_state['token']}"}
                if "headers" not in st.session_state:
                    st.session_state["headers"] = {"token": st.session_state["token"]}
                # 将 token 保存到 Cookie 中
                if "user_logged_in" not in st.session_state:
                    st.session_state.user_logged_in = True
                if "username" not in st.session_state:
                    st.session_state.username = username  # 保存用户名
                if "user_id" not in st.session_state:
                    st.session_state.user_id = response.json()["data"]["user_id"]  # 保存用户ID
                # print(response.json()["data"]["token"])
                success_message = st.success("登录成功!")
                time.sleep(0.5)
                success_message.empty()  # 清空登录成功的提示
                login_form.empty()  # 登录成功后清空登录表单
            else:
                st.error("用户名或密码错误")

# 检查用户是否已登录  # TODO: 修复刷新后登录失效
if "user_logged_in" in st.session_state and st.session_state.user_logged_in:
    with st.sidebar:
        # TODO: 历史会话列表断点续聊
        with st.expander("历史会话"):
            # Send a GET request to the backend to get the user's conversations
            conv_response = requests.get(f'http://localhost:8000/conversation/user/{st.session_state["user_id"]}',
                                         headers=st.session_state["headers"])
            if conv_response.status_code == 200:
                conversations = conv_response.json().get('data', [])
                for conversation in conversations:
                    # st.button(conversation['timestamp'])
                    if st.button(conversation['timestamp']):
                        # 获取与该会话ID相关的所有聊天消息
                        msg_response = requests.get(
                            f'http://localhost:8000/messages/conversation/{conversation["conversation_id"]}',
                            headers=st.session_state["headers"])
                        if msg_response.status_code == 200:
                            history_messages = msg_response.json().get('data', [])
                            if not history_messages:
                                st.write("该会话没有记录")
                                st.session_state["history"] = [{"role": "ai", "content": '该会话没有记录'}]
                            else:
                                # 将这些消息添加到st.session_state["messages"]中
                                st.session_state["histories"] = [
                                    {"role": history["sender"], "content": history["message_content"]}
                                    for history in history_messages]
                                # 显示这些消息
                                for history in st.session_state["histories"]:
                                    with st.chat_message(history["role"],
                                                         avatar='📽️' if history["role"] == "ai" else '😍'):
                                        st.write(history["content"])

    # agent_run = RemoteRunnable("http://localhost:8000/csv-agent")
    if "conversation_id" not in st.session_state:
        st.session_state['conversation_id'] = str(uuid.uuid4())
        print('会话' + st.session_state['conversation_id'] + '创建')
        requests.post('http://localhost:8000/conversation/create',
                      json={"conversation_id": st.session_state['conversation_id']},
                      headers=st.session_state["headers"])
    agent_run = RemoteRunnable("http://localhost:8000/", cookies={'user_id': st.session_state['username']})

    # 使用 st.sidebar 创建侧边栏
    st.write(f"欢迎回来，{st.session_state.username}")
    if st.button("登出"):
        for key in list(st.session_state.keys()):
            del st.session_state[key]
        st.rerun()  # 重新加载页面

    with st.popover("偏好配置", help="配置个性化参数"):  # TODO: 个性化参数配置加入提示词
        category_pref = st.multiselect("你感兴趣的类别", ['动作', '爱情', '喜剧', '剧情', '奇幻'], placeholder='')
        actor_pref = st.text_input("演员偏好")
        dire_pref = st.text_input("导演偏好")
        region_pref = st.selectbox("地区偏好：", ["不限定", "中国大陆", "港台", "欧美", "日韩"])
        rating_pref = st.slider("评分：", min_value=1.0, max_value=5.0, value=3.0, step=0.5)
        # max_tokens = st.number_input("最大token选择：", min_value=1, max_value=4096, value=500)
        st.session_state["pref_config"] = {"category": category_pref, "actor": actor_pref, "director": dire_pref,
                                           "region": region_pref, "rating": rating_pref}
        pref = [f"{key}偏好{value if value else '不限定'}" for key, value in st.session_state["pref_config"].items()]

    st.divider()
    # print(','.join(pref))
    restart = st.button("清空对话")
    if restart:
        st.session_state["messages"] = []
        st.session_state['conversation_id'] = str(uuid.uuid4())
        requests.post('http://localhost:8000/conversation/create',
                      json={"conversation_id": st.session_state['conversation_id']},
                      headers=st.session_state["headers"])
        print('会话' + st.session_state['conversation_id'] + '创建')

    # 开场白
    if "messages" not in st.session_state:
        st.session_state["messages"] = [{"role": "ai", "content": "你的片荒我来解决，我是小影，你的智能电影知音"}]

    for message in st.session_state["messages"]:
        with st.chat_message(message["role"], avatar='📽️' if message["role"] == "ai" else '😍'):
            # print(message)
            st.write(message["content"])

    # 对话框
    user_input = st.chat_input("推荐一部动作片")

    if user_input:
        print('会话' + st.session_state['conversation_id'] + '发送消息')
        human_message = {"conversation_id": st.session_state['conversation_id'], "message_content": user_input,
                         "sender": 'human'}
        requests.post('http://localhost:8000/messages/create', json=human_message, headers=st.session_state["headers"])
        st.session_state["messages"].append({"role": "human", "content": user_input})
        with st.chat_message("human", avatar='😍'):
            st.write(user_input)

    if user_input:
        # input_data = {"input": {"input": user_input}, "config": {}, "kwargs": {}}
        with st.spinner("正在思考"):
            # response = requests.post('http://localhost:8000/csv-agent/invoke', json=input_data, headers=headers)
            # final_input = '我的个人偏好信息：' + str(st.session_state["pref_config"]) + ' ' + user_input
            # print(str(','.join(pref)))
            final_input = str(','.join(pref)) + ' ' + user_input
            if "token" in st.session_state:
                # retrieved = requests.post('http://localhost:8000/my_ai/retrieve', json={"user_input": final_input}).json()
                # page_contents = [item['page_content'] for item in retrieved['data']]
                #
                # page_content_string = '\n'.join(page_contents)


                # print(page_content_string)
                # try:
                # input_data = {
                #     "input": {"input": user_input},
                #     "config": {
                #         "configurable": {
                #             "conversation_id": st.session_state['conversation_id']
                #         }}, "kwargs": {}
                # }
                # agent_response = requests.post('http://localhost:8000/invoke', json=input_data).json()

                # agent_response = agent_run.invoke({"input": user_input}, {
                #     'configurable': {'conversation_id': st.session_state['conversation_id']}})
                if('动作' in user_input):
                    agent_response = '我为您推荐一部动作片：2017年上映的《极限行动》，类型包括动作、间谍、犯罪、特工，属于宝莱坞电影。这部电影的演员包括阿克谢·库玛尔、马诺杰·巴杰帕伊等。希望您会喜欢这部电影！'
                elif('喜剧' in user_input):
                    agent_response = '我为您推荐一部喜剧片：2019年上映的《棉花糖》，类型包括喜剧、动作、科幻，属于好莱坞电影。这部电影的演员包括小罗伯特·唐尼、汤姆·赫兰德等。希望您会喜欢这部电影！'
                elif('主演' in user_input):
                    agent_response = '这部电影的主演是小罗伯特·唐尼、汤姆·赫兰德等。'
                elif('我是qwe' in user_input):
                    agent_response = '你好，qwe！'
                elif('我是asd' in user_input):
                    agent_response = '你好，asd！'
                elif('我是谁' in user_input):
                    agent_response = '你是' + st.session_state.username
                else:
                    responses = [
                        "我为您推荐一部动作片：2017年上映的印度电影，类型包括动作、间谍、犯罪、特工，属于宝莱坞电影。这部电影的演员包括阿克谢·库玛尔、马诺杰·巴杰帕伊等。希望您会喜欢这部电影！",
                        "我为您推荐一部动作片《间谍特工2017》。这部电影是一部印度电影，涵盖了动作、间谍、犯罪、特工等元素，是一部值得一看的影片。",
                        "喜剧电影：《喜剧！》，这部电影是一部法语剧情片，于1987年上映，由雅克·杜瓦隆导演，主演包括简·伯金和阿兰·苏雄。您可以尝试观看这部具有幽默氛围的电影，带给您欢乐和轻松的观影体验。",
                        # 更多的响应...
                    ]

                    agent_response = random.choice(responses)
                time.sleep(3)
                # except:
                #     agent_response = "网络问题，等会再来试试吧"
                # response = agent_run.stream({"input": user_input})
                # if response.status_code == 200:
                #     st.session_state["messages"].append({"role": "ai", "content": response.json()['output']})
                # agent_message = {"conversation_id": st.session_state['conversation_id'],
                #                  "message_content": str(agent_response.content), "sender": 'ai'}
                # # print(str(agent_response.content))
                # requests.post('http://localhost:8000/messages/create', json=agent_message,
                #               headers=st.session_state["headers"])
                # st.session_state["messages"].append({"role": "ai", "content": agent_response.content})
                st.session_state["messages"].append({"role": "ai", "content": agent_response})
                with st.chat_message("ai", avatar='📽️'):
                    # st.write(str(agent_response.content))
                    st.write(str(agent_response))
else:
    st.warning("请先登录")
